import { z } from "zod";
import { CodeIndexOrchestrator } from "../services/orchestrator.js";

export const clearIndexSchema = z.object({
  confirm: z.boolean().default(false).describe("Set to true to confirm clearing the index"),
});

export type ClearIndexArgs = z.infer<typeof clearIndexSchema>;

export async function clearIndexTool(
  args: ClearIndexArgs,
  orchestrator: CodeIndexOrchestrator
): Promise<string> {
  if (!args.confirm) {
    return `⚠️ **Index Clearing Confirmation Required**

This action will:
- Delete all indexed code blocks from the vector database
- Clear the file hash cache
- Stop file watching
- Reset the index to its initial state

**To confirm, call this tool again with:** \`{ "confirm": true }\`

**Note:** You will need to re-index your codebase after clearing to restore search functionality.`;
  }

  try {
    console.log("Clearing code index...");
    
    await orchestrator.clearIndex();
    
    return `✅ **Index Successfully Cleared**

**Actions Completed:**
- ✅ Deleted all indexed code blocks from vector database
- ✅ Cleared file hash cache
- ✅ Stopped file watching
- ✅ Reset index state to standby

**Next Steps:**
- Use the \`index_codebase\` tool to index a new codebase
- The system is ready for fresh indexing

**Note:** All previous search data has been permanently removed.`;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    return `❌ Failed to clear index: ${errorMessage}

**Possible Issues:**
- Vector database connection problems
- Permission issues with cache files
- File system access errors

Please check your configuration and try again.`;
  }
}
